//
//  ZXUIImagePickerManager.h
//  Baby
//
//  Created by simon on 16/4/19.
//  Copyright © 2016年 sina. All rights reserved.
//
//  简介：UIKit类的相册，相机调用的管理类；（1）UIImagePickerController默认就支持DarkMode模式,我们无需修改适配；(2)支持照片修正。
//  1.相册：（1）系统支持<14.0，不支持多选；支持编辑功能；（2）支持image、实况、movie资源访问；
// （3）读取图片不需要隐私授权；iOS11开始，UIImagePickerController不需要请求访问相册权限，就能访问全部相册内容。
// （4）不去请求相册权限，就不会触发iOS14新增的"Limited Photo Library Access" 模式，系统默认就是不需要，但是当前已经是这种限制模式的时候，在选择完照片的时候依然会触发；
// （5）3.iOS14及以上当用户触发相册权限请求时，如果选择PHAuthorizationStatusLimited” ，或当前权限已经选择"PHAuthorizationStatusLimited"状态，也未进行适配，权限提示框就会在每次冷启动后打开相册时重新弹出。UIImagePickerController/PHPicker在选择照片后会弹出：触发弹窗询问用户是否需要修改所选照片。对于这种情况可通过在Info.plist 中设置"Prevent limited photos access alert"的值为 YES 来阻止该弹窗反复弹出.
// （5）在iOS 14上使用PHPickerViewController选择照片；
//  2.相机：支持相机权限检查及提示，当没有权限的时候会自定义自动弹出默认引导提示;
//  3.注意：
//  （1）当我们使用UIImagePickerController的时候，默认它的页面是英文的，如果需要显示中文字，则必须在：Project-->Info-->Localizations 添加 Chinese简体中文; （2）如果加入了这个类，则必须添加隐私权限key-value；从2019年春季开始，如果应用程序的代码引用一个或多个访问敏感用户数据的api，所有提交到AppStore的访问用户数据的应用程序都必须包含一个目的字符串。如果您正在使用外部库或sdk，它们可能会引用需要目的字符串的api。虽然您的应用程序可能不使用这些api，但仍然需要一个目的字符串。
//  必须在info.plist文件中添加隐私权限提示key-value；
//  key1: Privacy - Photo Library Usage Description 读相册权限；iOS11之前的需要，iOS11开始不需要；
//  value：App需要您的同意，才能访问相册，以便在xxx上传您的图片
//  key2: Prevent limited photos access alert; 读相册限制照片数量阻止每次访问弹出权限；
//  value YES；
//  key3: Privacy - Photo Library Additions Usage Description; 存相册权限；
//  value：若不允许，您将无法保存xx的照片到本地相册
//  key4: Privacy - Camera Usage Description  相机拍摄权限
//  value：用于在xxx拍摄图片、视频以供上传
//  key5: Privacy - Microphone Usage Description 相机拍视频时的麦克风权限
//  value：用于在xxx中拍摄视频声音以供上传


//  2018.3.28； 优化代码；
//  2019.4.18 增加权限检查及提示的管理器；
//  2020.3.31 优化代码，增加属性控制；增加image图片修正；
//  2020.8.26 研究原照片大小及记录
//  2020.8.27 解决在拍照后出现异常，回调image是nil的处理；
//  2021-7-31 增加是否拍照存储照片的属性；
//  2021-11-09 增加合并方法及回调code

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import "CAIImagePickerManagerErrorConst.h"
#import <Photos/Photos.h>
#import "CAIUIImagePickerCameraOverlayApperance.h"
#import "CAICameraPhotoInfoModel.h"

NS_ASSUME_NONNULL_BEGIN



@class ZXUIImagePickerManager;
@protocol ZXUIImagePickerManagerDelegate <NSObject>

@optional


/// 只有一张照片/拍摄：完成选择、取消、因其它原因失败获取图片的回调；
/// @param info 选择之后的媒体信息；取消的话不反回；
/// @param image 选择之后的图片，如果有裁剪，就是裁减后的图片；取消的话不反回；
/// @param error 各种异常信息，包括没有权限，取消使用；
- (void)imagePickerControllerManager:(ZXUIImagePickerManager *)manager
       didFinishPickingImageWithInfo:(nullable NSDictionary<NSString *,id> *)info
                               image:(nullable UIImage *)image
                               error:(nullable NSError *)error;

- (void)imagePickerControllerManager:(ZXUIImagePickerManager *)manager
               imagePickerController:(UIImagePickerController *)picker
       didFinishPickingMediaWithInfo:(nullable NSDictionary<NSString *,id> *)info
                               image:(nullable UIImage *)image
                               error:(nullable NSError *)error API_DEPRECATED("-imagePickerControllerManager:didFinishPickingImageWithInfo:image:error: instead.", ios(2.0, 15.0));


/// 只有一张照片：选择实况照片回调；必须是非编辑模式才能选择返回实况照片；如果选择实况照片，且实现此方法，则不会回调didFinishPickingImageWithInfo:方法；
/// @param manager manager description
/// @param livePhoto livePhoto description
/// @param image image description
/// @param error error description
- (void)imagePickerControllerManager:(ZXUIImagePickerManager *)manager
           didFinishPickingLivePhoto:(nullable PHLivePhoto *)livePhoto
                               image:(nullable UIImage *)image
                               error:(nullable NSError *)error API_AVAILABLE(ios(9.1));

/// 拍摄多张照片唯一回调，及拍摄单张照片、选择照片的回调；如果实现这个，就不会回调上面的；
/// @param manager manager description
/// @param images images description
/// @param error error description
- (void)imagePickerControllerManager:(ZXUIImagePickerManager *)manager
              didFinishPickingImages:(nullable NSArray<UIImage *> *)images
                         imageModels:(nullable NSArray<CAIUIImagePickerCameraPhotoModel *> *)models
                               error:(nullable NSError *)error;

///// 未实现
//- (void)imagePickerControllerManager:(ZXUIImagePickerManager *)manager
//               didFinishPickingVideo:(UIImage *)coverImage
//                        sourceAssets:(PHAsset *)asset;

///拍照超过数量不允许
- (void)cameraMultiPhotoDidTakeLimitNumberNotAllow:(ZXUIImagePickerManager *)manager;



/// 返回拍照自定义处理后的水印图；如果watermask属性为YES；
/// @param manager manager description
/// @param orignalImage 拍照的图片
- (UIImage *)cameraWatermaskImage:(ZXUIImagePickerManager *)manager cameraImage:(nullable UIImage *)orignalImage;


@end

///此对象必须被上层对象引用，不然无法回调UIImagePickerControllerDelegate代理
@interface ZXUIImagePickerManager : NSObject<UIImagePickerControllerDelegate,UINavigationControllerDelegate>



@property(nonatomic, weak) id <ZXUIImagePickerManagerDelegate> delegate;

/**
 设置是否允许用户编辑选定的静态图像或电影。默认是NO；视频只有大于1秒的时候，才能编辑；
 即当相机拍完生成静态的视频&照片，或在相册中选完静态的视频&照片后，是否跳到编辑模式进行图片/视频剪裁。
 */
@property (nonatomic, assign) BOOL allowsEditing;


/// 设置当前使用摄像头的类型；default is UIImagePickerControllerCameraDeviceRear
@property(nonatomic) UIImagePickerControllerCameraDevice cameraDevice;

/// default value is 10 minutes.
@property(nonatomic) NSTimeInterval videoMaximumDuration;
/// default value is UIImagePickerControllerQualityTypeMedium.
@property(nonatomic) UIImagePickerControllerQualityType videoQuality;

/// 设置是否每次检查权限;默认YES;
@property (nonatomic, assign) BOOL alwayCheckAuthorization;


/// 设置是否允许拍照的照片存储到本地相册；默认NO不允许；//2021-7-31
@property (nonatomic, assign) BOOL allowWriteToSavedPhotos;

/// 配置外观，默认nil；
@property (nonatomic, strong, nullable) CAIUIImagePickerCameraOverlayApperance *cameraOverlayApperance;

/// 自定义相机拍照是否需要水印
@property (nonatomic, assign) BOOL watermask;


@property (nonatomic, copy) NSString *location;


/// 调用ActionSheet弹窗，可以自己选择单选相册或相机
/// @param sourceController presentingViewController的对象；
- (void)presentPhotoActionSheetToImagePickerWithSourceController:(UIViewController *)sourceController;


/// 调用系统单拍相机：拍单张照片
/// @param sourceController presentingViewController的对象；
- (void)presentCameraPhotoWithSourceController:(UIViewController *)sourceController;


/// 调用系统单拍相机：拍单视频--弹出视频捕捉时有警告：Snapshotting a view (0x11ff0a510, CAMPreviewView) that has not been rendered at least once requires afterScreenUpdates:YES.
/// @param sourceController presentingViewController的对象；
- (void)presentCameraMovieWithSourceController:(UIViewController *)sourceController;


/// 调用系统单拍相机：是否允许拍单照片、是否允许拍单视频
/// @param sourceController sourceController description
/// @param allowTakePhoto 是否允许拍单照片
/// @param allowTakeVideo 是否允许拍单视频
- (void)presentCameraWithSourceController:(UIViewController *)sourceController
                           allowTakePhoto:(BOOL)allowTakePhoto
                           allowTakeVideo:(BOOL)allowTakeVideo;

/// 调用定制相机拍照:能拍多张；自定义UIImagePickerController相机
/// @param sourceController sourceController description
/// @param maxTakePhotoNum 最多几张
- (void)presentCameraMultiPhotoWithSourceController:(UIViewController *)sourceController
                                    maxTakePhotoNum:(NSInteger)maxTakePhotoNum;



/// 调用单选相册--iOS14废弃，使用PHPicker多选照片
/// @param sourceController presentingViewController的对象；
- (void)presentPhotoLibraryWithSourceController:(UIViewController *)sourceController;


- (void)dismissCamera;

@end

NS_ASSUME_NONNULL_END

/*
 #import "ZXUIImagePickerManager.h"
 #import "AliOSSUploadManager.h"

<ZXUIImagePickerManagerDelegate>
 
 @property (nonatomic, strong) ZXUIImagePickerManager *imagePickerVCManager;
 @property (nonatomic, strong) NSMutableArray *mImages;
 @property (nonatomic, strong) NSMutableArray *photosMArray;
 
 @implementation ******
 
 
 //初始化照片／拍照选择
 - (ZXUIImagePickerManager *)imagePickerVCManager
 {
     if (!_imagePickerVCManager) {
         ZXUIImagePickerManager *manager = [[ZXUIImagePickerManager alloc] init];
         manager.delegate = self;
         _imagePickerVCManager = manager;
     }
     return _imagePickerVCManager;
 }
 
 - (NSMutableArray *)photosMArray
 {
     if (!_photosMArray) {
         _photosMArray = [NSMutableArray array];
     }
     return _photosMArray;
 }
 
 - (void)initImagePickerVCManager {
    
     //初始化oss上传
     [[AliOSSUploadManager sharedInstance] initAliOSSWithSTSTokenCredential];
     //是否需要获取图片信息，长宽
     [AliOSSUploadManager sharedInstance].getPicInfo = YES;
 }
 
 - (IBAction)shareAction:(UIButton *)sender {
 
     [self.imagePickerVCManager presentActionSheetToImagePickerWithSourceController:self];
 }
*/


#pragma mark -ZXUIImagePickerManagerDelegate

/*
//例1： 直接上传图片后加入到网络图片数组；
 
- (void)zxImagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info image:(nonnull UIImage *)image
{
   // NSData *imageData = UIImageJPEGRepresentation(image, 1);
    NSData *imageData = [WYUtility zipNSDataWithImage:image];
    self.navigationController.navigationBar.userInteractionEnabled = NO;

    [MBProgressHUD zx_showLoadingWithStatus:@"正在上传" toView:self.view];
    WS(weakSelf);
    [[AliOSSUploadManager sharedInstance]putOSSObjectSTSTokenInPublicBucketWithUserId:USER_TOKEN uploadingData:imageData progress:^(int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend) {
        
    } singleComplete:^(id imageInfo,NSString*imagePath,CGSize imageSize) {
        
        [MBProgressHUD zx_hideHUDForView:weakSelf.view];
        weakSelf.navigationController.navigationBar.userInteractionEnabled = YES;

        //这里处理上传图片
         NSURL *picUrl = [NSURL ossImageWithResizeType:OSSImageResizeType_w200_hX relativeToImgPath:imagePath];
         ZXPhoto *photo = [ZXPhoto photoWithOriginalUrl:imagePath thumbnailUrl:picUrl.absoluteString];
         photo.width = imageSize.width;
         photo.height = imageSize.height;
         photo.type = ZXAssetModelMediaTypePhoto;
         [weakSelf.photosMArray addObject:photo];

    } failure:^(NSError *error) {
 
        weakSelf.navigationController.navigationBar.userInteractionEnabled = YES;
        [MBProgressHUD zx_showError:[error localizedDescription] toView:weakSelf.view];
    }];
}
 - (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
     
      CHSVisitSignInUploadPicTableCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([CHSVisitSignInUploadPicTableCell class]) forIndexPath:indexPath];
      cell.picCollectionView.delegate = self;
      [cell setData:self.photosMArray];
      return cell;
 }
*/

/*
//例2： 直接先加入到本地图片数组，后续在提交数据的时候逐个上传；
 
 - (NSMutableArray *)mImages
 {
     if (!_mImages) {
         _mImages = [NSMutableArray arrayWithCapacity:3];
     }
     return _mImages;
 }
 
 
- (void)zxImagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info image:(nonnull UIImage *)image
{
    [self.mImages addObjectsFromArray:photos];
    [self.tableView reloadData];
}
 - (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
     
      CHSVisitSignInUploadPicTableCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([CHSVisitSignInUploadPicTableCell class]) forIndexPath:indexPath];
      cell.picCollectionView.delegate = self;
      [cell setData:self.mImages];
      return cell;
 }
 
 //本地上传数据+图片
 - (void)postDataAction:(UIButton *)sender
 {
     if (self.contentCell.textView.text.length<5)
     {
         [UIAlertController zx_presentGeneralAlertInViewController:self withTitle:NSLocalizedString(@"老板，生意回复不能少于5个字哦～", nil) message:nil cancelButtonTitle:nil cancleHandler:nil doButtonTitle:NSLocalizedString(@"知道了", nil) doHandler:nil];
         return;
     }
     
     WYPromptGoodsType goodsType = [self.contentCell getGoodsPromptType];
     if (goodsType ==WYPromptGoodsType_NOSelect)
     {
         [MBProgressHUD zx_showError:NSLocalizedString(@"请选择是否现货", nil) toView:self.view];
         return;
     }
     [MBProgressHUD zx_showLoadingWithStatus:NSLocalizedString(@"正在提交", nil) toView:self.view];
     //如果有图片则先上传图片；
     if (self.mImages.count>0)
     {
         NSMutableArray *tempMArray = [NSMutableArray array];
         __block NSInteger currentIndex = 0;
         WS(weakSelf);
         [self.mImages enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
             if(idx == 0){
                //清空数据
                [self.photosMArray removeAllObjects];
             }
             UIImage *image = (UIImage *)obj;
             NSData *imageData = [WYUtility zipNSDataWithImage:image];
             
             [[AliOSSUploadManager sharedInstance]putOSSObjectSTSTokenInPublicBucketWithUserId:USER_TOKEN fileCatalogType:OSSFileCatalog_tradeReply uploadingData:imageData progress:^(int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend) {
                 
             } singleComplete:^(id imageInfo,NSString*imagePath,CGSize imageSize) {
                 //这里处理上传图片
                 AliOSSPicUploadModel *model = [[AliOSSPicUploadModel alloc] init];
                 model.p = imagePath;
                 model.w = imageSize.width;
                 model.h = imageSize.height;
                 [tempMArray addObject:model];
                 currentIndex ++;
                 if (currentIndex == assets.count && tempMArray.count == assets.count){
                     [weakSelf.photosMArray addObjectsFromArray:tempMArray];
                     [weakSelf performSelector:@selector(uploadData)];
                 }
                 else if (currentIndex == assets.count && tempMArray.count < assets.count){
                     [MBProgressHUD zx_showError:[error localizedDescription] toView:weakSelf.view];
                 }
                 
             } failure:^(NSError *error) {
                currentIndex ++;
                if (currentIndex == assets.count && tempMArray.count < assets.count) {
                    [MBProgressHUD zx_showError:[error localizedDescription] toView:weakSelf.view];
                }
             }];
         }];
     }
     //如果没有图片则直接上传其它数据；
     else
     {
          [self performSelector:@selector(uploadData)];
     }
 }
*/
